var app = getApp()
// pages/answer-question/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        questions: [],
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.$ajax.getQuestions({
            "start": 1,
            "size": 20
        }, {isToken: true})

            .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                console.log(data, msg, status, header, statusCode, errMsg);

                if (status === '0') {
                    this.setData({
                        questions: data.questionList || []
                    })
                } else {
                    console.log('请求失败');
                }
            })

    },
    //  选择答案
    selectAnswer(e) {
        let {dataset} = e.currentTarget, {questions} = this.data;
        questions[dataset.questionIndex].selectIndex = dataset.answerIndex;
        this.setData({questions});
    },
    // 提交问题
    commitQuestions() {
        let noAnswerQuestions = this.data.questions.reduce((questions, item, index) => {
            if (item.selectIndex === '') questions.push(index);
            return questions;
        }, [])
        if (noAnswerQuestions.length) {
            wx.showToast({
                title: `${noAnswerQuestions.map(item => `第${item + 1}题`).join('、')}未作答`,
                icon: 'none',
                duration: 2000
            })
        } else {
            let score = 0;
            this.data.questions.forEach(item => {
                delete item.created;
                delete item.updated;
                item.select = item.selectIndex + 1;
                if (item.select == item.answer) score += 10;
            });
            wx.showLoading({
                title: '上传中...',
            });
            wx.$ajax.sendQuestionAnswer({
                score, questions: this.data.questions
            }, {isToken: true})
                .then(({data: {data, msg, status}, header, statusCode, errMsg}) => {
                    if (status === '0') {
                        app.globalData.change.lastTestScore = score;
                        wx.showToast({
                            title: `提交成功!`,
                            duration: 2000
                        })
                        setTimeout(() => {
                            wx.navigateBack();
                        }, 500)

                    } else {
                        wx.showToast({
                            title: `提交失败!`,
                            duration: 2000
                        })
                    }
                })

        }
    }
})